Jesus Fernandez

WCF Data Services: JSON format

Published on 18 May 20197 min read0 Comments
image

Having a publicly available API means that it should offer interoperability. In order to do this, we should take into consideration different message formats, such as XML, JSON, YAML, etc. Supporting other formats other than XML in WCF Data Services requires a custom implementation. This article aims to provide a simplified version of support for JSON

Our approach is to avoid significant changes in the way the service works. Luckily, WCF Data Services have built-in support for both ATOM (XML) and JSON. Therefore, we simply have to let the system know that the requested format is JSON and the API consumers will only have to make a change in the request URL by adding a parameter.

Support for JSON

The main thing we need to address is the format of the messages sent from or to the client, this can be done by implementing the IDispatchMessageInspector interface. This interface defines the methods that enable custom inspection or modification of inbound and outbound application messages. We will handle in our implementation the inbound message after a request has been received and the outbound message prior before sending the reply.

Next, we will create an attribute to configure the behavior in our service. However, keep in mind that attributes are a good option only if you know that support for the format not change. If you want to prioritize maintainability and ability to configure service behaviors without compiling your service, then you should look into moving the configuration to a configuration file (e.g.: web.config).

Usage

In order to use our newly created behavior, all we need to do is add the attribute to the data service, like so:

... and this is how the consumers of our API should request the format:

Caveats

In the above example, we assume UTF-8 as the encoding used. However, note that Data Services supports charset negotiation, so the implementation needs to be more sophisticated (including per-request) if clients use multiple charsets.